﻿using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using wlog.Model;

namespace wlog.Shell.Storage.Blob
{
    public class BlobListCommand : BlobStorageCommand
    {
        public override void Setup(string[] args)
        {
            base.Setup(args);
            base.CreateTask(() => { RunCommand(); });
        }
        public OutputChannel RunCommand()
        {
            try
            {
                CloudBlobClient blobAPI = GetBlobAccount();
                Results.WriteLine("Connected to: {0}", blobAPI.BaseUri);
                var root = blobAPI.GetContainerReference(objectName);
                if (root.Exists())
                {
                    Results.WriteLine("Found container: {0}", root.Name);
                    WriteBlobList(root);
                }
                else
                {
                    Results.WriteLine("Found container: {0} continuing showing all", root.Name);
                    var containers = blobAPI.ListContainers();
                    if (containers != null && containers.Any())
                    {
                        Results.WriteLine("Showing container total {0}", containers.Count());
                        Results.WriteLine("================================================================================");
                        Results.WriteKeyPair("ConatinerName", "Uri", 10);
                        Results.WriteLine("================================================================================");
                    }
                    else
                    {
                        Results.WriteLine("There is no Blob at {0}, would you like to create one ?", blobAPI.BaseUri);
                    }
                    foreach (var container in containers)
                    {
                        Results.WriteKeyPair(container.Name, container.Uri.AbsoluteUri, 10);
                        WriteBlobList(container);
                    }
                }

            }
            catch (Exception azureEx)
            {
                Results.WriteLine("Error listing Blob {0} ", azureEx.Message);
            }
            return Results;
        }

    }
}
